package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.beans.GlobalRoamingBeans;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DimenUtils;
import com.yuyh.library.utils.ScreenUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/9/8.
 */

public class LocationAllActivity extends BaseSwipeBackActivity implements AMap.OnCameraChangeListener, LocationSource, AMapLocationListener,
        AMap.CancelableCallback{

    private static final String TAG = "LocationAllActivity";
    private static final int SDK_PERMISSION_REQUEST = 127;
    @BindView(R.id.gaodemapView)
    MapView gaodemapView;
    @BindView(R.id.location_bt)
    ImageView location_bt;

    private AMap aMap;
    private UiSettings uiSetting;
    private Marker marker = null;

    double longitude = 0;
    double latitude = 0;
    double mylongitude = 0;
    double mylatitude = 0;

    private AMapLocationClient locationClient;//高德定位类
    private AMapLocationClientOption mLocationOption;

    PGService mPgService;
    GlobalRoamingBeans globalRoamingBeans ;

    public static void start(Activity activity ){
        Intent intent = new Intent(activity, LocationAllActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.near_person);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPgService = PGService.getInstance();
        gaodemapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = gaodemapView.getMap();
            Log.i("info","amap=="+aMap);
            if (aMap != null) {
                uiSetting = aMap.getUiSettings();
                aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
            }
        }

        aMap.setOnCameraChangeListener(this);
        startLocation();
        getPersimmions();
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_location_all;
    }

    private void setGetLocation(){
        if (null==locationClient){
            startLocation();
        }else {
            locationClient.startLocation();//启动定位
        }

    }

    @TargetApi(23)
    protected void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION)) {
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                pos ++ ;
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }else {
                setGetLocation();
            }
        }else {
            //不用动态申请权限
            setGetLocation();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                return false;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Map<String, Integer> perms = new HashMap<String, Integer>();
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        setGetLocation();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.no_pawr_nouse), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void initMaker(double lat, double lut) {
        LatLng latLng = new LatLng(lut, lat);
        marker = aMap.addMarker(new MarkerOptions().position(latLng).title("").snippet("DefaultMarker").visible(true));
        marker.setPositionByPixels(DimenUtils.getScreenWidth() / 2, ScreenUtil.dp2px(150));//设置居中显示不随地图移动
        BitmapDescriptor bitmapDescriptor = marker.getIcons().get(1);
        marker.setIcon(bitmapDescriptor);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
    }

    //开启定位
    private void startLocation() {
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        uiSetting.setScaleControlsEnabled(true);//设置比例尺显示
        uiSetting.setMyLocationButtonEnabled(true);//显示定位按钮
        uiSetting.setZoomControlsEnabled(true);

    }

    @OnClick({R.id.location_bt })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back :
                scrollToFinishActivity();
                break;
            case R.id.location_bt:

                if (0 != longitude && 0 != latitude){
                    qqmy();
                }else {
                    showToast(getResources().getString(R.string.get_address_fail));
                }

                break;

        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        double longitude = cameraPosition.target.longitude;
        double latitude = cameraPosition.target.latitude;
        // Log.i("info", "==onCameraChange==" + cameraPosition);

        locationClient.stopLocation();
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        longitude = cameraPosition.target.longitude;
        latitude = cameraPosition.target.latitude;
//        point = new LatLonPoint(oncamerlatitude, oncamerlongitude);
        // Log.i("info","first=="+isfirstin+"  item="+isselectorItem);

        //Log.i("info", "==onCameraChangeFinish==" + cameraPosition);
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
//        mListener = onLocationChangedListener;
        Log.i(TAG, "activate: ======001=====");
        if (locationClient == null) {
            Log.i(TAG, "activate: ======002=====");
            //初始化定位
            locationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            locationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            locationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
//        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.i(TAG, "activate: ======004=====");
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
//                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                /*aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(
                        aMapLocation.getLatitude(), aMapLocation.getLongitude())));
*/
                CameraUpdateFactory.zoomTo(15);
//                amaplocatoion = aMapLocation;
//                //地址信息
//                address = aMapLocation.getAddress();
//                //城市
//                city = aMapLocation.getCity();
//                //省份
//                province = aMapLocation.getProvince();
//                //街道
//                street = aMapLocation.getStreet();
//                //区
//                district = aMapLocation.getDistrict();
//                //位置语意信息
//                description = aMapLocation.getDescription();
//                altitude = aMapLocation.getAltitude();
//                //街道号
//                streetNum = aMapLocation.getStreetNum();
//                //楼层信息
//                floor = aMapLocation.getFloor();
                //经度
                mylongitude = aMapLocation.getLongitude();
                //纬度
                mylatitude = aMapLocation.getLatitude();
                //poiname
//                poiName = aMapLocation.getPoiName();
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mylatitude, mylongitude), 15), this);

                Log.i(TAG, "activate: ======005====mylongitude="+mylongitude+"==mylatitude=="+mylatitude);
                initMaker(mylongitude, mylatitude);

                //marker.setAnimationListener(this);
                //smoothtoLocation(new LatLng(oncamerlatitude,oncamerlongitude),new LatLng(latitude,longitude));
//                Log.i("info", "定位成功" + "\n" + "adr==" + address + "\n" + "经度=" + longitude + " 纬度=" + latitude + "\n" + "poiname==" + poiName
//                        + "\n" + "city=" + city + "\n" + "省份=" + province + "\n" + "区=" + district + "\n" + "街道=" + street + "\n" + "街道号=" + streetNum + "\n" + "楼层=" + floor + "\n" + "位置语描述=" + description
//                );

            } else {
                Log.i(TAG, "定位失败" + aMapLocation.getErrorCode() + aMapLocation.getErrorInfo());
                // String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                //  Log.e("AmapErr", errText);
            }

    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onCancel() {

    }

    /**
     * 请求漫游信息
     */
    private void qqmy() {

        mPgService.findNearby(ToolsUtils.getMyUserId(), ""+latitude, ""+longitude, "", "0").subscribe(new AbsAPICallback<GlobalRoamingBeans>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.get_data_fail));
            }

            @Override
            public void onNext(GlobalRoamingBeans mglobalRoamingBeans) {
                globalRoamingBeans = mglobalRoamingBeans ;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        GlobalRoamingUserListActivity.start(LocationAllActivity.this,globalRoamingBeans,mylongitude,mylatitude
                                ,longitude,latitude);

                    }
                });
//                transOut();
            }
        });
    }

}
